package com.activitycode.activity.user;


import java.io.File;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.activitycode.city.CityDbHelp;
import com.activitycode.datamodel.RegionInfo;
import com.activitycode.datamodel.UserResult;
import com.activitycode.datamodel.model.UserInfo;
import com.activitycode.main.MainActivity;
import com.activitycode.net.HttpUtil;
import com.activitycode.net.Httpclient;
import com.activitycode.tools.EncryTools;
import com.activitycode.tools.ImageChooseTools;
import com.activitycode.util.BaseTask;
import com.activitycode.util.CommConstant;
import com.activitycode.util.CommConstant.TaskResult;
import com.activitycode.util.DataBaseHelper;
import com.activitycode.util.JacksonUtil;
import com.activitycode.util.SharedPreferrenceManager;
import com.duostec.zhuyue.pets.R;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.Dao.CreateOrUpdateStatus;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;


public class RegisterEditActivity extends Activity{
	private String from;
	private TextView titleText;
	private ImageButton titleBtn,submitBtn;
	private ImageView userHead,sexImg;
	private EditText userName;
	private TextView cityText,agreeText;
	private LinearLayout sexLinear,cityLinear;
	//数据库
	private DataBaseHelper dbHelper;
	private Dao<UserInfo, String> userInfoDao;
	private Dao<RegionInfo, String> regionInfoDao;
	private UserInfo info;
	private String userTel ,pass;
	//图像缓存相关
	public ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	private String headUrl = "";
	
	//区域相关
	private  String provinceFlag = "0", cityFlag = "0", districtFlag = "0";
	//citydb
	private CityDbHelp dbHelp;
	private Boolean isMale = true;
	//滚轮相关
	final Handler mHandler = new Handler();

	
	List<RegionInfo> provinceList;
	List<RegionInfo> cityList;
	List<RegionInfo> areaList;
	
	String[] provinceArray;
	String[] cityArray;
	String[] areaArray;
	
	ProviceCityAreaAdapter provinceAdapter;
	ProviceCityAreaAdapter cityAdapter;
	ProviceCityAreaAdapter areaAdapter;
	
	RegionInfo noneInfo;
	
	private ImageChooseTools imageChooseTools;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ui_register_edit);
		imageChooseTools = new ImageChooseTools(RegisterEditActivity.this);
		initOptions();
		initView();
		initData();
		
	}
	
	
	@Override
	protected void onResume(){
//		RegionInfo infos = queryRegion(SharedPreferrenceManager.getCityName(getApplicationContext()));
//		if(infos!=null){
//			cityText.setText(infos.region_name);
//			provinceFlag = infos.parent_id;
//			cityFlag = infos.region_id;
//		}
		
		super.onResume();
	}
	
	private void initView(){
		titleText = (TextView) this.findViewById(R.id.title_user_name);
		titleText.setText("个人信息");
		titleBtn = (ImageButton) findViewById(R.id.title_user_back);
		titleBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				finish();
				
			}
			
		});
		submitBtn = (ImageButton) findViewById(R.id.user_edit_submit);
		submitBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				submit();
			}
			
		});
		
		userHead = (ImageView) this.findViewById(R.id.user_edit_head);
		userHead.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PopupWindow pop = getHeadWindow(RegisterEditActivity.this);
				pop.showAtLocation(arg0, Gravity.CENTER, 0, 0);
			}
			
		});
		userName = (EditText) this.findViewById(R.id.user_edit_master);
		
		sexImg = (ImageView) this.findViewById(R.id.user_edit_sex);
		cityText = (TextView) this.findViewById(R.id.user_edit_city);
		agreeText = (TextView) this.findViewById(R.id.user_edit_agree);
		agreeText.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(RegisterEditActivity.this, AgreeActivity.class);					
				startActivity(intent);
			}
			
		});
		sexLinear = (LinearLayout) this.findViewById(R.id.user_edit_sex_linear);
		sexLinear.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(isMale){
					isMale = false;
				}else{
					isMale = true;
				}
				sexImg.setSelected(isMale);
			}
			
		});
		cityLinear = (LinearLayout) this.findViewById(R.id.user_edit_city_linear);
		cityLinear.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PopupWindow pop = getCityWindow(RegisterEditActivity.this);
				pop.showAtLocation(arg0, Gravity.CENTER, 0, 0);
			}
			
		});
		
	}
	
	private void initData(){
		pass = getIntent().getStringExtra("pass");
		userTel = getIntent().getStringExtra("user_name");
		dbHelper = DataBaseHelper.getHelper(getApplicationContext());
		try {
			userInfoDao = dbHelper.getUserInfoDao();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dbHelp = CityDbHelp.getHelper(getApplicationContext());
		try {
			regionInfoDao = dbHelp.getRegionInfoDao();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		sexImg.setSelected(isMale);
		
		noneInfo = new RegionInfo();
		noneInfo.region_id="0";
		noneInfo.parent_id="0";
		noneInfo.agency_id="0";
		noneInfo.region_name=" ";
		noneInfo.region_type="3";
	}
	
	
	
	private RegionInfo queryRegion(String id){
		RegionInfo infos = null ;
		try {
			infos = regionInfoDao.queryForId(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return infos;
	}
	
	private void initProvince(){
		
		try {
			provinceList = regionInfoDao.queryBuilder().where().eq("parent_id", "0").query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(provinceList!=null&&provinceList.size()>0){
			Log.i("Task", "size="+provinceList.size());
			provinceArray = new String[provinceList.size()];
			for(int i=0;i<provinceList.size();i++){
				Log.i("Task", "name="+""+provinceList.get(i).region_id+"*"+provinceList.get(i).parent_id+"*"+provinceList.get(i).region_name+"*"+provinceList.get(i).region_type+"*"+provinceList.get(i).agency_id);
				provinceArray[i] = ""+provinceList.get(i).region_name;
				
			}
			
		}else{
//			try {
//				provinceList = regionInfoDao.queryForAll();
//			} catch (SQLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			Log.i("Task", "size="+provinceList.size());
			provinceArray = new String[0];
		}
	}
	
	private void initCity(String parentId){
		try {
			cityList = regionInfoDao.queryBuilder().where().eq("parent_id", ""+parentId).query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(cityList!=null&&cityList.size()>0){
			cityArray = new String[cityList.size()];
			for(int i=0;i<cityList.size();i++){
				cityArray[i] = cityList.get(i).region_name;
			}
		}else{
			cityArray = new String[1];
			cityList.add(noneInfo);			
			cityArray[0] = cityList.get(0).region_name;
		}
	}
	
	private void initArea(String parentId){
		try {
			areaList = regionInfoDao.queryBuilder().where().eq("parent_id", ""+parentId).query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(areaList!=null&&areaList.size()>0){
			areaArray = new String[areaList.size()];
			for(int i=0;i<areaList.size();i++){
				areaArray[i] = areaList.get(i).region_name;
			}
		}else{
			areaArray = new String[1];
			areaList.add(noneInfo);			
			areaArray[0] = areaList.get(0).region_name;
		}
	}
	
	/**
	 * 设置头像的信息	 
	 */
	private void setHeadImage(String url){
		
		
		if( url!=null){
        	imageLoader.displayImage("file://"+url, userHead, options, animateFirstListener);
        }
		
	}
	
	/**
	 * 初始化图片缓存操作
	 */
	private void initOptions(){
		options = new DisplayImageOptions.Builder()		
		.cacheInMemory(true)
		.cacheOnDisc(true)
		.considerExifParams(true)
		.displayer(new RoundedBitmapDisplayer(100))
		.build();
	}
	
	/**
	 * 图片缓存下载监听
	 * @author Administrator
	 *
	 */
	private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}
	/**
	    * 返回时 清空缓存
	    */
	@Override
	public void onBackPressed() {
		AnimateFirstDisplayListener.displayedImages.clear();
		super.onBackPressed();
	}
	
	
	private void submit(){
		if(HttpUtil.isnet(getApplicationContext())){
			String name = userName.getText().toString();
			
			
			String city = cityText.getText().toString();
			
			if(name.equals("")){
				Toast.makeText(getApplicationContext(), "姓名不能为空", Toast.LENGTH_SHORT).show();
				return;
			}else if(city.equals("")){
				Toast.makeText(getApplicationContext(), "选择您的城市", Toast.LENGTH_SHORT).show();
				return;
			}else if(headUrl.equals("")){
				Toast.makeText(getApplicationContext(), "选择您的头像", Toast.LENGTH_SHORT).show();
				return;
			}
			
					
			String url = CommConstant.SERVICE_HOST_IP_LAN+CommConstant.REGISTER;			
			Map<String, String> arg = EncryTools.getEncryMap();			
			arg.put("nick_name", ""+name);
			arg.put("user_name", ""+userTel);
			arg.put("password", ""+pass);
			if(isMale){
				arg.put("sex", ""+0);
			}else{
				arg.put("sex", ""+1);
			}			
			arg.put("province", ""+provinceFlag);
			arg.put("city", ""+cityFlag);
			arg.put("town", ""+districtFlag);
			
			
			UserEditActivityTask task = new UserEditActivityTask(this,url,arg);
			task.execute();
		}else{
			Toast.makeText(getApplicationContext(), 
					getResources().getString(R.string.error_item1), Toast.LENGTH_SHORT).show();
		}
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	 {
	  super.onActivityResult(requestCode, resultCode, data);
	 
	     if(resultCode==RESULT_OK)
	     {
	    	 switch (requestCode) {
	         case ImageChooseTools.CHOOSE_PICTURE: // 调用Gallery返回的
	        	 ImageChooseTools.doCropPhoto(RegisterEditActivity.this, ImageChooseTools.getGalleryUri(RegisterEditActivity.this, data),true);
	        	 break;
	            case ImageChooseTools.PHOTO_WITH_CAMERA: // 照相机程序返回的

	            	ImageChooseTools.doCropPhoto(RegisterEditActivity.this, ImageChooseTools.getTakeUri(),true);
	              break;
	            case ImageChooseTools.PHOTO_PICKED_WITH_CROP: // 图片裁剪操作	            	
	            	 Bitmap headPhoto = ImageChooseTools.getCropBitmap(data);
	            	 String imagePath = Environment.getExternalStorageDirectory() + "/"+RegisterEditActivity.this.getPackageName()+"/cache/tamp/"+System.currentTimeMillis()+".jpg";
	            	 File dir = new File(Environment.getExternalStorageDirectory() + "/"+RegisterEditActivity.this.getPackageName()+"/cache/tamp/");
	            	 if(!dir.exists()){
	            		 dir.mkdirs();
	            	 }
	            	 boolean saveResult = ImageChooseTools.saveJPGE_After(
	 						headPhoto,100,imagePath);	
		             if(saveResult){
		            	 headUrl = imagePath;
		            	 RegisterEditActivity.this.setHeadImage(headUrl);
		             }else{
		            	 Toast.makeText(RegisterEditActivity.this, "选取图片失败", Toast.LENGTH_SHORT).show();
		             }
	             
	             if(!headUrl.equals("")){
//	            	 uploadHead();
	             }
	             
	             break;

	         }
	     }
	 }
	

	public PopupWindow getHeadWindow(final Context ct) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(userName.getWindowToken(), 0);
		
		View view = getLayoutInflater().inflate(R.layout.popupwindow_headchoose ,null, false);
		
	    Button take = (Button) view.findViewById(R.id.takePhoto );
	    Button album = (Button) view.findViewById(R.id.album );
        LinearLayout popupwindowLinear = (LinearLayout) view.findViewById(R.id.popupwindow_linear);
        view.getBackground().setAlpha(99);
        
        
        final PopupWindow popupWindow = new PopupWindow(view,LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        view = null;
//		popupWindow.setContentView(view);
//		popupWindow.setWidth(width);
//		popupWindow.setHeight(height/3);
		
		popupWindow.setFocusable(true);
		
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable()); //使按返回键能够消失
		
		take.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				imageChooseTools.doTakePhoto(RegisterEditActivity.this);
				popupWindow.dismiss();
			}
			
		});
		album.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				imageChooseTools.doGalleryPhoto(RegisterEditActivity.this);
				popupWindow.dismiss();
			}
			
		});
		popupwindowLinear.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
			}
			
		});
		
		return popupWindow;
	}
	
	
	public PopupWindow getCityWindow(Context ct) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(userName.getWindowToken(), 0);
		
		View view = getLayoutInflater().inflate(R.layout.popupwindow_citychoose ,null, false);		
	    Button make = (Button) view.findViewById(R.id.pop_city_make );
	    Button cancle = (Button) view.findViewById(R.id.pop_city_cancle );
        LinearLayout popupwindowLinear = (LinearLayout) view.findViewById(R.id.pop_city_linear);
        view.getBackground().setAlpha(99);
        //滚轮相关
        final WheelView provinceWheelView = (WheelView)view.findViewById(R.id.pop_city_provice);
        final WheelView cityWheelView = (WheelView)view.findViewById(R.id.pop_city_city);
        final WheelView areaWheelView = (WheelView)view.findViewById(R.id.pop_city_area);     	
        
        initProvince();
        provinceAdapter = new ProviceCityAreaAdapter(RegisterEditActivity.this, provinceArray, 0);
		provinceWheelView.setViewAdapter(provinceAdapter);
		initCity(provinceList.get(0).region_id);
		cityAdapter = new ProviceCityAreaAdapter(RegisterEditActivity.this, cityArray, 0);
		cityWheelView.setViewAdapter(cityAdapter);
		if(cityArray.length>0){
			initArea(cityList.get(0).region_id);
		}		
		areaAdapter = new ProviceCityAreaAdapter(RegisterEditActivity.this, areaArray, 0);
		areaWheelView.setViewAdapter(areaAdapter);
        final PopupWindow popupWindow = new PopupWindow(view,LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        view = null;		
		popupWindow.setFocusable(true);		
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable()); //使按返回键能够消失		
		make.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mHandler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						StringBuilder sb = new StringBuilder();
						sb.append(provinceArray[provinceWheelView.getCurrentItem()]);
						
						sb.append(" "+cityArray[cityWheelView.getCurrentItem()]);
						
						sb.append(" "+areaArray[areaWheelView.getCurrentItem()]);
						Log.i("Task", "area="+sb);
						cityText.setText(sb);
						provinceFlag = provinceList.get(provinceWheelView.getCurrentItem()).region_id;
						cityFlag = cityList.get(cityWheelView.getCurrentItem()).region_id;
						districtFlag = areaList.get(areaWheelView.getCurrentItem()).region_id;
//						Toast.makeText(UserEditActivity.this, sb.toString()+" key:"+DqxxUtils.findPrimaryKey(db, TABLE_NAME, sb.toString()), Toast.LENGTH_SHORT).show();
					}
				}, 400);
				popupWindow.dismiss();
			}
			
		});
		cancle.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				popupWindow.dismiss();
			}
			
		});
		popupwindowLinear.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
			}
			
		});
		OnWheelScrollListener privinceScrollListener = new OnWheelScrollListener() {
			
			@Override
			public void onScrollingStarted(WheelView wheel) {
			}
			
			@Override
			public void onScrollingFinished(WheelView wheel) {
				int currentItem = wheel.getCurrentItem();
				provinceFlag = ""+provinceList.get(currentItem).region_id;
				initCity(provinceFlag);
				cityAdapter = new ProviceCityAreaAdapter(RegisterEditActivity.this, cityArray, 0);
				cityWheelView.setViewAdapter(cityAdapter);
				cityWheelView.setCurrentItem(0);
				if(cityArray.length<=0){
					areaArray = new String[0];
					cityFlag = "0";
					districtFlag = "0";
				}else{
					 cityFlag = cityList.get(0).region_id;					 
					 initArea(cityFlag);
					 if(areaArray.length<=0){
						 districtFlag = "0";
					 }
				}

				areaAdapter = new ProviceCityAreaAdapter(RegisterEditActivity.this, areaArray, 0);
				areaWheelView.setViewAdapter(areaAdapter);
				areaWheelView.setCurrentItem(0);
			}
		};
		
		provinceWheelView.addScrollingListener(privinceScrollListener);
		OnWheelScrollListener cityScrollListener = new OnWheelScrollListener() {
			
			@Override
			public void onScrollingStarted(WheelView wheel) {
			}
			
			@Override
			public void onScrollingFinished(WheelView wheel) {
				int currentItem = wheel.getCurrentItem();
				cityFlag = ""+cityList.get(currentItem).region_id;				
				initArea(cityFlag);
				areaAdapter = new ProviceCityAreaAdapter(RegisterEditActivity.this, areaArray, 0);
				areaWheelView.setViewAdapter(areaAdapter);
			}
		};
		cityWheelView.addScrollingListener(cityScrollListener);
		return popupWindow;
	}
	
	public class ProviceCityAreaAdapter extends ArrayWheelAdapter<String> {
		private int currentItem;
		private int currentValue;
		
		public ProviceCityAreaAdapter(Context context, String[] items, int current) {
			super(context, items);
			this.currentValue = current;
		}
		
		
		public void setCurrentValue(int value){
			this.currentValue = value;
		}
		
		@Override
		protected void configureTextView(TextView view) {
			super.configureTextView(view);
//			if (currentItem == currentValue) {
//				view.setTextColor(0xFF0000F0);
//			}
			view.setTypeface(Typeface.SANS_SERIF);
		}
		
		@Override
		public View getItem(int index, View convertView, ViewGroup parent) {
			currentItem = index;
			return super.getItem(index, convertView, parent);
		}
		
	}
	
	
	
	
	public class UserEditActivityTask extends BaseTask<Void, String, TaskResult>{
		public static final String TAG = "UserEditActivityTask";
		private String httpUrl;
		private Map<String, String> argList;
		private ProgressDialog progress=null;
		private Context context;
		private String msg = "";
		
		public UserEditActivityTask(Context ct ,String url, Map<String, String> arg){
			this.httpUrl = url;
			this.argList = arg;
			this.context = ct;
		}
		
		@Override
		public void onPreExecute() 
		{
			if(progress==null){
				showPD(context);
			}
			
		}

		@Override
		public TaskResult doInBackground(Void... params) {
			// TODO Auto-generated method stub
			TaskResult taskResult = TaskResult.ACRIVATE;
			String result = "";
			File file = new File(headUrl);
			try {
				result = Httpclient.uploadSubmit(httpUrl, argList, file,"Filedata");
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
//			String result = Httpclient.postData(httpUrl, argList);
			JacksonUtil json = JacksonUtil.getInstance();			
			UserResult res = json.readValue(result, UserResult.class);
			if(res==null){
				
				taskResult = TaskResult.CANCELLED;
			}else{
				msg = res.msg;
				if(res.result){
					taskResult = TaskResult.OK;
					try {
						if(info==null){
//							try {
//								info = userInfoDao.queryForId(res.user_name);
//							} catch (SQLException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
							info = new UserInfo();
						}	
						info.user_id = res.user_name;
						info.setSex(argList.get("sex")); 
						
						CreateOrUpdateStatus cou = userInfoDao.createOrUpdate(info);
						SharedPreferrenceManager.saveUserId(getApplicationContext(), res.user_name);
						Log.i("Task", "create="+cou.isCreated()+"##update="+cou.isUpdated());
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else{
					
					taskResult = TaskResult.ERROR;
				}
			}
			return taskResult;
		}
		
		@Override
		public void onPostExecute(TaskResult result) 
		{
			if(progress!=null){
				progress.dismiss();
			}
			File headImg = new File(headUrl);
			if(headImg.exists()){
				headImg.delete();
			}
			switch(result){
			
				case OK:
					
					Intent intent = new Intent();
					intent.setClass(RegisterEditActivity.this, MainActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					sendBroad();
					finish();
//					Toast.makeText(getApplicationContext(), ""+msg, Toast.LENGTH_SHORT).show();
					break;
				case ERROR:
					
					Toast.makeText(getApplicationContext(), ""+msg, Toast.LENGTH_SHORT).show();
					break;
				case CANCELLED:
					
//					Toast.makeText(getApplicationContext(), ""+msg, Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		}
		protected void showPD(Context paramContext)
		  {
		    progress = new ProgressDialog(paramContext);
		    progress.setMessage("正在注册...");
		    progress.setCanceledOnTouchOutside(false);
		    progress.show();
		  }
	}
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {  
			
			finish();
                return true;
	    }
		if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
			
//			finish();
            return true;
		}
		return super.dispatchKeyEvent(event);
		}
	
	private void sendBroad(){
		   Intent intent = new Intent();
		   intent.setAction(LoginActivity.finishFlag);
		   
		   //要发送的内容
		   intent.putExtra("author", "Abel");

		   //发送 一个无序广播
		   RegisterEditActivity.this.sendBroadcast(intent);
		}
	
	
}